package com.atyjh.reggie.service.impl;

import com.atyjh.reggie.dto.Result;
import com.atyjh.reggie.entity.Category;
import com.atyjh.reggie.entity.Dish;
import com.atyjh.reggie.entity.Setmeal;
import com.atyjh.reggie.exception.CategoryException;
import com.atyjh.reggie.mapper.CategoryMapper;
import com.atyjh.reggie.service.ICategoryService;
import com.atyjh.reggie.service.IDishService;
import com.atyjh.reggie.service.ISetMealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author yjh
 * @since jdk1.8.0_311 2022.06.16
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Resource
    private IDishService dishService;
    @Resource
    private ISetMealService setMealService;

    @Override
    public Result<Page<Category>> pageDish(Integer page, Integer pageSize) {

//        分页构造器
        Page<Category> categoryPage = new Page<>(page, pageSize);

//        选择构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        page(categoryPage, lqw);

        return Result.success(categoryPage);
    }

    @Override
    public Result<String> delete(Long id) {

//        查询当前分类是否关联了菜品
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        dlqw.eq(Dish::getCategoryId, id);
        long count1 = dishService.count(dlqw);
        if (count1 > 0) {
//            抛出自定义异常
            throw new CategoryException("当前分类关联了菜品，不能删除！");
        }
//        查询当前分类是否关联了套餐
        LambdaQueryWrapper<Setmeal> slqw = new LambdaQueryWrapper<>();
        slqw.eq(Setmeal::getCategoryId, id);
        long count2 = setMealService.count(slqw);
        if (count2 > 0) {
            throw new CategoryException("当前分类关联了套餐，不能删除！");
        }
        removeById(id);
        return Result.success("删除成功！");
    }
}






